using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using ECommerce.Library;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using ECommerce.DAL;
using Entity;
using System.IO;

public partial class admin_send_newsletter : SiteAdminBasePage
{
    public int _newsId;
    string mailBody = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;
        if (!IsPostBack)
        {
            BindControl();
        }
    }

    private void BindControl()
    {
        ddlNewsLetterGroup.DataSource = NewsletterGroup.GetAllActiveGroups();
        ddlNewsLetterGroup.DataTextField = "GroupName";
        ddlNewsLetterGroup.DataValueField = "GroupId";
        ddlNewsLetterGroup.DataBind();
        StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/templates/polana_newsletter.txt"));
        string templateContent = reader.ReadToEnd();
        reader.Close();
        fckEmailBody.Value = templateContent;
    }

    private string imageHandler(Match match)
    {
        // gets the imgs src attribute from the Regular Expression's match
        string src = match.Groups[1].Value;

        Uri uri = null;
        // try to create a valid Uri by the img's src
        try
        {
            uri = new Uri(src);
        }
        catch
        {
        }
        if (uri != null && uri.IsAbsoluteUri)
        {
            return "src=\"" + uri.ToString() + "\"";
        }
        else
        {
            return "src=\"" + (SiteGlobals.BaseUrl + (Request.ApplicationPath == "/" ? src.Remove(0, 1) : src.Replace(Request.ApplicationPath, string.Empty).Remove(0, 1))) + "\"";
        }
    }
    protected void Create_Click(object sender, EventArgs e)
    {
        try
        {
            Page.Validate();
            if (Page.IsValid)
            {
                string subject = SiteUtility.BindStringInput(tbxSubject.Text, SecurityLevel.One);
                string emailBody = fckEmailBody.Value;  // tbxEmailBody.Text;
                Newsletter newsletter = new Newsletter(subject, emailBody);
                if (cbxIndividualEmail.Checked)
                {
                    string[] emails = tbxEmailTo.Text.Split(',');
                    foreach (string email in emails)
                    {
                        if (RegExUtil.IsEmail(email.Trim()))
                        {
                            NewsletterSubscriber subscriber = new NewsletterSubscriber();
                            subscriber.Email = email.Trim();
                            subscriber.SubscriberName = email.Trim();
                            newsletter.Subscribers.Add(subscriber);
                        }
                    }
                }
                else
                {
                    int subscriberGroupId = int.Parse(ddlNewsLetterGroup.SelectedItem.Value);
                    newsletter.Subscribers = NewsletterSubscriber.GetSubscribtersByGroup(subscriberGroupId);
                }
                Newsletter.SendNewsletter(newsletter);
                Newsletter.Create(newsletter);
                uccResponseMessage.SetSuccessMessage("Newsletter sent");
                uccResponseMessage.Visible = true;

            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage("Failed to send Newsletter");
            uccResponseMessage.Visible = true;
        }


        
    }
    private string generateEmailBody(string mailBody,string subject)
    {
        CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.NewsletterEmail.ToString());
        string mailText = string.Empty;
        if (tblEmailTemplate.Count > 0)
        {
            mailText = tblEmailTemplate[0].EmailBody;
            mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
            mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
            mailText = mailText.Replace("###SiteUrl###", SiteSettings.SiteBaseUrl);
            mailText = mailText.Replace("<##MessageBody##>", mailBody);
            mailText = mailText.Replace(" <##Subject##>", subject);

        }
        return mailText;
    }
   
    private void SendCampaign(string campaignId)
    {
        
    }

    protected void btnPreview_Click(object sender, EventArgs e)
    {
        try
        {
            Page.Validate();
            if (Page.IsValid)
            {
                string subject = SiteUtility.BindStringInput(tbxSubject.Text, SecurityLevel.One);
                string emailBody = fckEmailBody.Value;
                Newsletter newsletter = new Newsletter(subject, emailBody);
                Session["SendNewsLetter"] = Newsletter.PreviewNewsletter(newsletter);
                uccResponseMessage.Visible = false;
                ClientScript.RegisterStartupScript(this.GetType(), "ShowPreview", "<script> window.open('newsletter-preview.aspx','newpage','scrollbars=yes,status=no,width=700,height=600'); </script>");
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage("Failed to generate Newsletter preview");
            uccResponseMessage.Visible = true;
        }
    }
}
